<?php

namespace Home\Biz;

use Home\Biz\StringBiz;
use Org\Util\String;

class DealerBiz {
	
	
	//线下发货操作
	public static function partofexpress() {
		
		$wharehouse_id = I("wharehouse_id");
		$carrier_id = I("carrier_id");
		$send_date= I("send_date");
		$remark = I("remark");
		$items = I("items");
		
		$order_logistic_id=CommonBiz::getExpressId ( "Express" );
		$order_id='';
		$qty=0;
		foreach ($items as $item) {
			$order_id=$item['order_id'];
			$qty+=$item['qty'];
		}
		
		//1、判断订单状态是否可以发货
		$order_info_en = M ( 'order_info' )->where ( "order_id='%s'", $order_id )->find ();
		$order_status= $order_info_en['order_status'];
		if($order_status =='22' || $order_status=='33'){
			$order_detail_lst=M('order_detail')->where("order_id ='%s'",$order_id)->select();
			/* foreach ($order_detail_lst as $d_detail){
				if($d_detail['qty']==$d_detail['ship_qty']){	//已发货
					return "已发货";
				}
				if(($d_detail['qty']==$d_detail['rma_qty'])&& ($d_detail['qty']!=$d_detail['ship_qty'])){	//尚未发货已取消
					return "尚未发货已取消";
				}
			} */
			$order_detail_lt=M('order_detail')->where("order_id ='%s' and qty != ship_qty and qty!=rma_qty ",$order_id)->select();
			 if(sizeof($items)== sizeof($order_detail_lt)){
			 //全部发货
			 	$order_info_en_ls ['ship_qty'] = $qty;
			 	$order_info_en_ls ['order_status'] = 31;
			 }else{
			 //部分发货
			 	$order_info_en_ls ['ship_qty'] = $qty;
			 	$order_info_en_ls ['order_status'] = 33;
			 }
			 M ( 'order_info' )->where ( "order_id='%s'", $order_id )->save ( $order_info_en_ls );
			 
			 $order_change_log = array (
			 		"order_id" => $order_id,
			 		"order_status" => $order_info_en_ls ['order_status'],
			 		"order_status_text" => StringBiz::getPromoterOrderStatusText ( $order_info_en_ls ['order_status'] ),
			 		"create_user" => 'whaleyinfo.order dealer.partofexpress',
			 		"create_date" => date ( "y-m-d H:i:s", time () )
			 );
			 M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
			 
		}else{
			return "此订单不可发货";
		}
		
		$order_consign = array (
				'order_logistic_id' => $order_logistic_id,
				'order_id' => $order_id,
				'ship_qty' => $qty,
				'shipping_warehouse' => $wharehouse_id,
				'send_date' => $send_date,
				'remark' => $remark,
				'carrier_id' => $carrier_id,
				'create_user' => "whaleyinfo.order DealerBiz.partofexpress",
				'create_date' => date ( "y-m-d H:i:s", time () )
		);
		M ( 'order_consignment' )->add ( $order_consign );
		
		foreach ($items as $item) {
			$order_consign_detail = array (
					'id' => CommonBiz::getExpressId ( "Express" ),
					'oid' => $item['oid'],
					'order_logistic_id' => $order_logistic_id,
					// 实发数量是总数减去已发货的数量
					'ship_qty' => $item['qty'] - $item['ship_qty'],
					'code_69' =>  $item['code'],
					'create_user' => "whaleyinfo.order DealerBiz.partofexpress",
					'create_date' => date ( "y-m-d H:i:s", time () )
			);
			M ( 'order_consignment_detail' )->add ( $order_consign_detail );
			
			$order_detail_en_ls['ship_qty']=$item['qty'];
			M ( 'order_detail' )->where ( "oid='%s'", $item['oid'] )->save ( $order_detail_en_ls );
		}
		
		$post_data = array(
				"orderNo"=>$order_logistic_id,
				"type"=>"DEALER"
		);
		
		$result=CommonBiz::httpPostJson(C('Api.DealerShippingUrl'), $post_data);
		$response = json_decode($result['response']);
		
	}
	
	public static function caculateTotalPage($totalCount, $pageSize) {
		$count = intval ( $totalCount / $pageSize );
		
		$countLeft = $totalCount % $pageSize;
		
		if ($countLeft != 0) {
			$count = $count + 1;
		}
		
		return $count;
	}
	public static function validateDealerAmount($dealer_id,$dealer_channel, $amount_type, $amount) {
		$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='%s' and dealer_channel=%s", $dealer_id ,$dealer_channel)->find ();
		if (empty ( $dealer_en )) {
			return "该经销商不存在！";
		} else {
			
			if (! is_numeric ( $amount )) {
				return "请输入数字！";
			}
			
			if ($amount < 0) {
				
				return "请输入大于0 的金额！";
			}
			
			switch ($amount_type) {
				case 11 :
					// 金额增加
					
					return;
				case 21 :
					// 金额减少
					if ($dealer_en ['amount'] - $amount < 0) {
						return "经销商余额不足！";
					}
					return;
				default :
					return "非法操作！";
			}
		}
	}
	
	public static function validateDealerCashBackAmount($dealer_id,$dealer_channel, $amount_type, $amount) {
		$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='%s' and dealer_channel=%s", $dealer_id ,$dealer_channel)->find ();
		if (empty ( $dealer_en )) {
			return "该经销商不存在！";
		} else {
				
			if (! is_numeric ( $amount )) {
				return "请输入数字！";
			}
				
			if ($amount < 0) {
	
				return "请输入大于0 的金额！";
			}
				
			switch ($amount_type) {
				case 11 :
					// 金额增加
						
					return;
				case 21 :
					// 金额减少
					if ($dealer_en ['cashback_amount'] - $amount < 0) {
						return "经销商后返余额不足！";
					}
					return;
				default :
					return "非法操作！";
			}
		}
	}
	
	public static function updateDealerAmount($dealer_id, $amount_type, $amount,$remark) {
		
		$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_id )->find ();

		 
		
			switch ($amount_type) {
				case 11 :
					// 金额增加
					$end_mount = 	$dealer_en['amount'] + $amount;
					$dealer_amount = array(
							"dealer_amount_id"	=> self::generateDealerAmountId(),
							"dealer_id" =>$dealer_id,
							"dealer_name" =>$dealer_en['dealer_name'],
							"amount_kind" =>1,
							"amount_type" =>$amount_type,
							"amount" =>$amount,
							"begin_amount" =>$dealer_en['amount'],
							"end_amount" =>$end_mount,
							"remark" =>$remark,
							"status" =>1,
							'create_user' => "whaleyinfo.order DealerBiz.updateDealerAmount",
							'create_date' => date ( "y-m-d H:i:s", time () )
					);
					M('dealer_info')->where( "dealer_id='%s'", $dealer_id)->setField("amount",$end_mount);
					M('dealer_amount')->add($dealer_amount);
					break;
				case 21 :
					// 金额减少
					$end_mount = 	$dealer_en['amount'] - $amount;
					$dealer_amount = array(
							"dealer_amount_id"	=> self::generateDealerAmountId(),
							"dealer_id" =>$dealer_id,
							"dealer_name" =>$dealer_en['dealer_name'],
							"amount_kind" =>2,
							"amount_type" =>$amount_type,
							"amount" =>$amount,
							"begin_amount" =>$dealer_en['amount'],
							"end_amount" =>$end_mount ,
							"remark" =>$remark,
							"status" =>1,
							'create_user' => "whaleyinfo.order DealerBiz.updateDealerAmount",
							'create_date' => date ( "y-m-d H:i:s", time () )
					);
					M('dealer_info')->where( "dealer_id='%s'", $dealer_id)->setField("amount",$end_mount);
					M('dealer_amount')->add($dealer_amount);
					break;
				
			}
		}
		
		public static function updateDealerCashBackAmount($dealer_id, $amount_type, $amount,$remark) {
		
			$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_id )->find ();
		
				
		
			switch ($amount_type) {
				case 11 :
					// 金额增加
					$end_mount = 	$dealer_en['cashback_amount'] + $amount;
					$dealer_amount = array(
							"dealer_amount_id"	=> self::generateDealerAmountId(),
							"dealer_id" =>$dealer_id,
							"dealer_name" =>$dealer_en['dealer_name'],
							"amount_kind" =>1,
							"amount_type" =>$amount_type,
							"amount" =>$amount,
							"begin_amount" =>$dealer_en['cashback_amount'],
							"end_amount" =>$end_mount,
							"remark" =>$remark,
							"status" =>1,
							'create_user' => "whaleyinfo.order DealerBiz.updateDealerCashBackAmount",
							'create_date' => date ( "y-m-d H:i:s", time () )
					);
					M('dealer_info')->where( "dealer_id='%s'", $dealer_id)->setField("cashback_amount",$end_mount);
					M('dealer_cashback_amount')->add($dealer_amount);
					break;
				case 21 :
					// 金额减少
					$end_mount = 	$dealer_en['cashback_amount'] - $amount;
					$dealer_amount = array(
							"dealer_amount_id"	=> self::generateDealerAmountId(),
							"dealer_id" =>$dealer_id,
							"dealer_name" =>$dealer_en['dealer_name'],
							"amount_kind" =>2,
							"amount_type" =>$amount_type,
							"amount" =>$amount,
							"begin_amount" =>$dealer_en['cashback_amount'],
							"end_amount" =>$end_mount ,
							"remark" =>$remark,
							"status" =>1,
							'create_user' => "whaleyinfo.order DealerBiz.updateDealerCashBackAmount",
							'create_date' => date ( "y-m-d H:i:s", time () )
					);
					M('dealer_info')->where( "dealer_id='%s'", $dealer_id)->setField("cashback_amount",$end_mount);
					M('dealer_cashback_amount')->add($dealer_amount);
					break;
		
			}
		}
		
		
	
	public static function validateDealer($dealer_en) {
		if (empty ( $dealer_en ['dealer_name'] )) {
			return "经销商名称不能为空！";
		}
		if (empty ( $dealer_en ['dealer_type'] )) {
			return "经销商类型不能为空！";
		}
		if (empty ( $dealer_en ['discount_rate'] )) {
			if ($dealer_en ['discount_rate'] != '0' && empty ( $dealer_en ['discount_rate'] )) {
				return "经销商折扣不能为空！";
			}
		} else {
			$max_rate = C ( 'DealerConfig.MaxDiscountRate' );
			$min_rate = C ( 'DealerConfig.MinDiscountRate' );
			
			if (! is_numeric ( $dealer_en ['discount_rate'] )) {
				
				return '经销商折扣必须为数字类型！';
			}
			
			if ($dealer_en ['discount_rate'] < 0) {
				return "经销商折扣必须大于等于0";
			}
			if ($dealer_en ['discount_rate'] > $max_rate) {
				
				return '经销商折扣点大于系统配置最大值' . $max_rate;
			}
			if ($dealer_en ['discount_rate'] < $min_rate) {
				
				return '经销商折扣点小于系统配置最小值' . $min_rate;
			}
		}
		
		if (empty ( $dealer_en ['cash_back_rate'] )) {
// 			if ($dealer_en ['cash_back_rate'] != '0' && empty ( $dealer_en ['cash_back_rate'] )) {
// 				return "经销商后返折扣不能为空！";
// 			}
			$dealer_en ['cash_back_rate'] =0;
		} else {
			$max_rate = C ( 'DealerConfig.MaxCashBackRate' );
			$min_rate = C ( 'DealerConfig.MinCashBackRate' );
				
			if (! is_numeric ( $dealer_en ['cash_back_rate'] )) {
		
				return '经销商后返折扣必须为数字类型！';
			}
				
			if ($dealer_en ['cash_back_rate'] < 0) {
				return "经销商后返折扣必须大于等于0";
			}
			if ($dealer_en ['cash_back_rate'] > $max_rate) {
		
				return '经销商后返折扣点大于系统配置最大值' . $max_rate;
			}
			if ($dealer_en ['cash_back_rate'] < $min_rate) {
		
				return '经销商后返折扣点小于系统配置最小值' . $min_rate;
			}
		}
		
		
		if (empty ( $dealer_en ['business_leader'] )) {
			return "业务联系人不能为空！";
		}
		
		if (empty ( $dealer_en ['business_leader_cellphone'] )) {
			return "业务联系人电话不能为空！";
		}
		if (empty ( $dealer_en ['area_name'] )) {
			return "大区信息不能为空！";
		}
		if (empty ( $dealer_en ['province_id'] )) {
			return "省区信息不能为空！";
		}
		if (empty ( $dealer_en ['city_id'] )) {
			return "市区信息不能为空！";
		}
		if (empty ( $dealer_en ['operation_pattern'] )) {
			return "操作模式不能为空！";
		}
		if (empty ( $dealer_en ['registered_capital'] )) {
			if ($dealer_en ['registered_capital'] != '0' && empty ( $dealer_en ['registered_capital'] )) {
				
				return "注册资本不能为空！";
			}
		} else {
			
			if (! is_numeric ( $dealer_en ['registered_capital'] )) {
				
				return "注册资本必须为数字类型！";
			}
			
			if ($dealer_en ['registered_capital'] < 0) {
				return "注册资本必须大于等于0";
			}
		}
		
		if (empty ( $dealer_en ['leal_person'] )) {
			return "法人代表不能为空！";
		}
		if (empty ( $dealer_en ['bank_name'] )) {
			return "开户行名称不能为空！";
		}
		if (empty ( $dealer_en ['bank_no'] )) {
			return "开户行账号不能为空！";
		}
		if (empty ( $dealer_en ['tax_no'] )) {
			return "税号不能为空！";
		}
		if (empty ( $dealer_en ['dealer_id_card_no'] )) {
			return "经销商身份证号码不能为空！";
		} else {
			
			if (! StringBiz::isIdentity ( $dealer_en ['dealer_id_card_no'] )) {
				
				return "身份证号码格式不合法,请检查！";
			}
		}
		
		if (empty ( $dealer_en ['business_license_no'] )) {
			return "营业执照号码不能为空！";
		}
		
		if (empty ( $dealer_en ['finance_leader'] )) {
			return "财务联系人不能为空！";
		}
		if (empty ( $dealer_en ['finance_leader_cellphone'] )) {
			return "财务联系人联系方式不能为空！";
		}
		if (empty ( $dealer_en ['invoice_address'] )) {
			return "发票地址不能为空！";
		}
		if (empty ( $dealer_en ['sign_status'] )) {
			return "签约状态不能为空！";
		}
		
// 		if (empty ( $dealer_en ['registered_address'] )) {
// 			return "发票注册地址不能为空！";
// 		}
// 		if (empty ( $dealer_en ['registered_tel'] )) {
// 			return "注册电话不能为空！";
// 		}
		return '';
	}
	public static function addDealer($dealer_en) {
		$add_user_en = array (
				'user_id' => $dealer_en ['user_id'],
				'user_name' => $dealer_en ['business_leader'],
				'real_name' => $dealer_en ['business_leader'],
				'cellphone' => $dealer_en ['business_leader_cellphone'],
				'account_source' => 8,
				'account_name' => $dealer_en ['dealer_name'],
				'province_id' => $dealer_en ['province_id'],
				'province_name' => $dealer_en ['province_name'],
				'city_id' => $dealer_en ['city_id'],
				'city_name' => $dealer_en ['city_name'],
				'status' => $dealer_en ['status'],
				'create_user' => "whaleyinfo.order DealerBiz.addDealer",
				'create_date' => date ( "y-m-d H:i:s", time () ) 
		);
		
		M ( 'user_info' )->add ( $add_user_en );
		M ( 'dealer_info' )->add ( $dealer_en );
	}
	public static function updateDealer($dealer_en) {
		$user_update_en = array (
				'user_id' => $dealer_en ['user_id'],
				'cellphone' => $dealer_en ['business_leader_cellphone'],
				'account_source' => 8,
				'account_name' => $dealer_en ['dealer_name'],
				'province_id' => $dealer_en ['province_id'],
				'province_name' => $dealer_en ['province_name'],
				'city_id' => $dealer_en ['city_id'],
				'city_name' => $dealer_en ['city_name'],
				'status' => $dealer_en ['status'],
				'update_user' => "whaleyinfo.order DealerBiz.updateDealer",
				'update_date' => date ( "y-m-d H:i:s", time () ) 
		);
		M ( 'user_info' )->where ( 'user_id="%s"', $user_update_en ['user_id'] )->save ( $user_update_en );
		M ( 'dealer_info' )->where ( 'dealer_id ="%s"', $dealer_en ['dealer_id'] )->save ( $dealer_en );
	}
	
	
	
	public static function queryDealerChargeAmountBySale ( $dealer_id,$dealer_name,$sale_id,$recharge_status, $pageSize, $index ){
		
		
		if (! empty ( $dealer_id )) {
			$condition_array ['dealer_id'] = array (
					'like',
					"'%" . $dealer_id . "%'"
			);
		}
		
		if (!empty ($dealer_name)) {
			$condition_array['dealer_name'] = array('like', "'%" . $dealer_name . "%'");
		}
		
		if (!empty ($recharge_status)) {
			$condition_array['recharge_status'] = array('=', $recharge_status);
		}
		
		$temp = array();
		$cn=0;
		if(sizeof($condition_array)>0){
			$temp[]=" AND ";
		}
		foreach ($condition_array as $key=>$val){
		
			$temp[] ="dealer_recharge.".$key.' ';
			$temp[] = join(" ", $val);
			if($cn != sizeof($condition_array)-1){
				$temp[]=" AND ";
			}
			$cn++;
		}
			
		$sql =  "exists (SELECT	*  FROM sale_dealer_relationship AS sdr  WHERE dealer_recharge.dealer_id = sdr.dealer_id
          AND sdr.sale_id ='".$sale_id ."'".join('',$temp).")";
		
		
		$lst_dealers_chargeamount = M ( 'dealer_recharge' )->field ()->where ( $sql )->order('create_date desc')->page ( $index, $pageSize )->select ();
		
		foreach ($lst_dealers_chargeamount as &$chargemount){
				
			$chargemount["recharge_status_text"] = StringBiz::getDealerRechargeTypeRevenueStatusText($chargemount['recharge_status']);
		}
		
		
		$totalCount = M ( 'dealer_recharge' )->where ( $sql )->count();
		// 		echo  M('')->getLastSql();
		// 		return ;
		$totalPage = self::caculateTotalPage ( $totalCount, $pageSize );
		$currentCount = $lst_dealers_chargeamount . $pageSize;
		
		$nextIndex = $index + 1;
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
		
		$resultMap = array (
				'datas' => $lst_dealers_chargeamount,
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index
		)
		;
		
		return $resultMap;
		
		
		
		
		
	}
	
	public static function queryDealerChargeAmountByPara ( $dealer_id,$dealer_name,$dealer_channel,$recharge_status, $pageSize, $index ){
		
		if (! empty ( $dealer_id )) {
			$condition_array ['dealer_id'] = array (
					'like',
					"'%" . $dealer_id . "%'"
			);
		}
		
		
		if (!empty ($dealer_name)) {
			$condition_array['dealer_name'] = array('like', "'%" . $dealer_name . "%'");
		}
		
		if (!empty ($recharge_status)) {
			//$condition_array['recharge_status'] = array('=', $recharge_status);
			$ext_sql="dr.recharge_status=$recharge_status";
		}

		$temp = array();
		$cn=0;
		if(sizeof($condition_array)>0){
			$temp[]=" AND ";
		}
		foreach ($condition_array as $key=>$val){
		
			$temp[] ="di.".$key.' ';
			$temp[] = join(" ", $val);
			if($cn != sizeof($condition_array)-1){
				$temp[]=" AND ";
			}
			$cn++;
		}
		if(!empty($ext_sql)){
			$temp[]= " AND ".$ext_sql;
		}
		$sql =  "exists (SELECT * FROM dealer_info AS di WHERE dr.dealer_id = di.dealer_id AND di.dealer_channel =".$dealer_channel ."".join('',$temp).")";
		
		
		
		
		$lst_dealers_chargeamount = M ( 'dealer_recharge' )->alias('dr')->field()->where ( $sql )->order('create_date desc')->page ( $index, $pageSize )->select ();
		
 		
		foreach ($lst_dealers_chargeamount as &$chargemount){
			
			$chargemount["recharge_status_text"] = StringBiz::getDealerRechargeTypeRevenueStatusText($chargemount['recharge_status']);
		}
		
		
		$totalCount = M ( 'dealer_recharge' )->alias('dr')->where ( $sql )->count();
				
		$totalPage = self::caculateTotalPage ( $totalCount, $pageSize );
		$currentCount = $lst_dealers_chargeamount . $pageSize;
		
		$nextIndex = $index + 1;
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
		
		$resultMap = array (
				'datas' => $lst_dealers_chargeamount,
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index
		)
		;
		
		return $resultMap;
		
	}
	
	public static function calcDealerCashBackAmountByPara( $dealer_id, $dealer_name,$start_date, $end_date ){
		
		$condition_array = array();
		
		if(!empty($dealer_id)){
			array_push($condition_array, "dl.dealer_id = '".$dealer_id."'");
		}
		
		if(!empty($dealer_name)){
			array_push($condition_array, "dl.dealer_name = '".$dealer_name."'");
		}
		if(!empty($start_date)){
			
			array_push($condition_array, "oc.send_date >= '$start_date'");
		}
		
		if(!empty($end_date)){
			array_push($condition_array, "oc.send_date <= '$end_date'");
			
		}
		
		array_push($condition_array, "o.order_type = 8 AND d.qty=d.ship_qty AND s.is_rebate = 1");
		
		$condition_sql = implode(' AND ', $condition_array);
			
		$lst_rrsStockOrder_en =M('order_info')->alias('o')->
		where($condition_sql)->
		Field("d.* ,dl.dealer_id,dl.dealer_name,dl.cash_back_rate , ROUND(d.payment_amount*dl.cash_back_rate,2) AS cash_amount  ,oc.send_date")->
		join("dealer_info  AS dl ON o.buyer_alipay_no = dl.dealer_id")->
		join("order_detail AS d ON o.order_id = d.order_id")->
		join("order_consignment AS oc ON oc.oid = d.oid")->
		join("whaley_product.sku  s ON d.sku_id = s.sku_id")->
		select();
		

		$total_dealer_cashback_amount=0;
		
		foreach ($lst_rrsStockOrder_en as  $key){
			$total_dealer_cashback_amount+=$key['cash_amount'];
		}
		
		return $total_dealer_cashback_amount;
		
	}
	
	public static function queryDealerAmountByPara($dealer_id, $amount_type, $dealer_channel,$start_date,$end_date, $pageSize, $index) {
		if (! empty ( $dealer_id )) {
			$condition_array ['dealer_id'] = array (
					'=',
					"'".$dealer_id."'"
			);
		}
		
		if (! empty ( $amount_type )) {
			$condition_array ['amount_type'] = array (
					'=',
					$amount_type 
			);
		}
		
		
		
		
		
		
		$temp = array();
		$cn=0;
		if(sizeof($condition_array)>0){
			$temp[]=" AND ";
		}
		foreach ($condition_array as $key=>$val){
		
			$temp[] ="da.".$key.' ';
			$temp[] = join(" ", $val);
			if($cn != sizeof($condition_array)-1){
				$temp[]=" AND ";
			}
			$cn++;
		}
			
		$sql =  "exists (SELECT * FROM dealer_info AS di WHERE da.dealer_id = di.dealer_id AND di.dealer_channel =".$dealer_channel ."".join('',$temp)." and da.create_date between '$start_date' and '$end_date' ".")";
			
		
		$lst_dealers_amount = M ( 'dealer_amount' )->alias('da')->field ()->where ( $sql )->order('create_date desc')->page ( $index, $pageSize )->select ();
		
		$totalCount = M ( 'dealer_amount' )->alias('da')->where ( $sql )->count();

		$totalPage = self::caculateTotalPage ( $totalCount, $pageSize );
		$currentCount = $lst_dealers_amount . $pageSize;
		
		$nextIndex = $index + 1;
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
		
		$resultMap = array (
				'datas' => $lst_dealers_amount,
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index 
		)
		;
		
		return $resultMap;
	}
	
	
	public static function queryDealerCashBackAmountByPara($dealer_id, $amount_type, $dealer_channel,$start_date,$end_date, $pageSize, $index) {
		if (! empty ( $dealer_id )) {
			$condition_array ['dealer_id'] = array (
					'=',
					"'".$dealer_id."'"
			);
		}
	
		if (! empty ( $amount_type )) {
			$condition_array ['amount_type'] = array (
					'=',
					$amount_type
			);
		}
	
	
	
	
	
	
		$temp = array();
		$cn=0;
		if(sizeof($condition_array)>0){
			$temp[]=" AND ";
		}
		foreach ($condition_array as $key=>$val){
	
			$temp[] ="dca.".$key.' ';
			$temp[] = join(" ", $val);
			if($cn != sizeof($condition_array)-1){
				$temp[]=" AND ";
			}
			$cn++;
		}
			
		$sql =  "exists (SELECT * FROM dealer_info AS di WHERE dca.dealer_id = di.dealer_id AND di.dealer_channel =".$dealer_channel ."".join('',$temp)." and dca.create_date between '$start_date' and '$end_date' ".")";
			
	
		$lst_dealers_amount = M ( 'dealer_cashback_amount' )->alias('dca')->field ()->where ( $sql )->order('create_date desc')->page ( $index, $pageSize )->select ();
	
		$totalCount = M ( 'dealer_cashback_amount' )->alias('dca')->where ( $sql )->count();
		// 		echo  M('')->getLastSql();
		// 		return ;
		$totalPage = self::caculateTotalPage ( $totalCount, $pageSize );
		$currentCount = $lst_dealers_amount . $pageSize;
	
		$nextIndex = $index + 1;
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
	
		$resultMap = array (
				'datas' => $lst_dealers_amount,
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index
		)
		;
	
		return $resultMap;
	}
	
	public static function queryDealerByPara($dealer_name, $dealer_type, $business_leader, $area_name, $sign_status, $status, $k3_code,$dealer_channel, $pageSize, $index) {
		if (! empty ( $dealer_name )) {
			$condition_array ['dealer_name'] = array (
					'like',
					"'%" . $dealer_name . "%'" 
			);
		}
		
		if (! empty ( $dealer_type )) {
			$condition_array ['dealer_type'] = array (
					'=',
					$dealer_type 
			);
		}
		
		if (! empty ( $business_leader )) {
			$condition_array ['business_leader'] = array (
					'like',
					"'%" . $business_leader . "%'" 
			);
		}
		
		if (! empty ( $area_name )) {
			$condition_array ['area_name'] = array (
					'like',
					"'%" . $area_name . "%'" 
			);
		}
		
		if (! empty ( $sign_status )) {
			$condition_array ['sign_status'] = array (
					'=',
					$sign_status 
			);
		}
		
		if (! empty ( $status )) {
			$condition_array ['status'] = array (
					'=',
					$status 
			);
		}
		
		if (! empty ( $dealer_channel )) {
			$condition_array ['dealer_channel'] = array (
					'=',
					$dealer_channel
			);
		}
		
		//线下渠道经销商
// 		$condition_array ['dealer_channel'] = array (
// 				'=',
// 				1
// 		);
		
	if (! empty ( $k3_code )) {
				
			if($k3_code == 1 ){
				//$condition_array ['k3_code'] = array (	'neq',	""	);
				$sql_k3 ="k3_code IS NOT  NULL  AND k3_code !='' AND k3_code != 'None'";
			}else {
				//$condition_array ['k3_code'] = array ('eq',	""	);

				$sql_k3 = "(k3_code IS NULL OR k3_code = 'None' OR k3_code = '')";
				//$condition_array['_query'] = "k3_codeISNULL&k3_code='None'&k3_code=&_logic=or";
			}
		}
		
		
		
		$temp = array();
		$cn=0;
		
		foreach ($condition_array as $key=>$val){
		
			$temp[] ="".$key.' ';
			$temp[] = join(" ", $val);
			if($cn != sizeof($condition_array)-1){
				$temp[]=" AND ";
			}
			$cn++;
		}
			
		

		
		if(sizeof($condition_array)>0){
					
			if(!empty($sql_k3)){
				
				$sql = "".join("",$temp)." AND ".$sql_k3;
			}else{
				$sql = "".join("",$temp);
			}
			
		}else{
			
			$sql = $sql_k3;
		}
		
		
		
// 		echo sizeof($condition_array);		
// 		echo $sql;
// 		return ;
		$lst_dealers = M ( 'dealer_info' )->field ()->where ( $sql )->page ( $index, $pageSize )->select ();
//  		echo $k3_code;
// 		echo M('')->getLastSql();
// 		return;
		$totalCount = M ( 'dealer_info' )->where ( $sql )->count ();
		$totalPage = self::caculateTotalPage ( $totalCount, $pageSize );
		$currentCount = $lst_dealers . $pageSize;
		
		$nextIndex = $index + 1;
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
		
		$resultMap = array (
				'datas' => $lst_dealers,
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index 
		)
		;
		
		return $resultMap;
	}
	public static function generateUserId() {
		$seq = 1000000 + CommonBiz::getNewSeq ( 'user_id' );
		return 'U' . $seq;
	}
	
	public static function generateDealerAmountId() {
		$seq = 10000000 + CommonBiz::getNewSeq ( 'AmountId' );
		return 'DAR' . $seq;
	}
	
	
	public static function generateDealerAmountChangeId() {
		$seq = 100000000 + CommonBiz::getNewSeq ( 'changeId' );
		return 'DACL' . $seq;
	}
	
	public static function generateDealerAmountChargeId() {
		$seq = 1000000000 + CommonBiz::getNewSeq ( 'chargeId' );
		return 'DAC' . $seq;
	}
	public static function generateDealerId() {
		$seq = 1000000 + CommonBiz::getNewSeq ( 'dealer_id' );
		return 'DL' . $seq;
	}
	public static function queryDealerByIdAndName($dealer_id) {
		$con = array ();
		if (! empty ( $dealer_id )) {
			array_push ( $con, "dealer_id='$dealer_id'" );
		}
		$dealer_en = M ( 'dealer_info' )->field ()->where ( join ( " AND ", $con ) )->find ();
		
		$resultMap = array (
				'dealer' => $dealer_en 
		);
		
		if ($dealer_en != null) {
			$user_id = $dealer_en ['user_id'];
			$lst_user_address = M ( 'user_address' )->field ()->where ( "user_id='$user_id'" )->select ();
			
			if ($lst_user_address != null) {
				$resultMap = array (
						'dealer' => $dealer_en,
						'address' => $lst_user_address 
				);
			}
		}
		
		return $resultMap;
	}



public  static  function  shipDealerInfoExcel($params_en){
	
	
	Vendor('phpExcel.PHPExcel');
	$objPHPExcel = new  \PHPExcel();
	
	$objPHPExcel->setActiveSheetIndex(0);
	$objPHPExcel->getActiveSheet()->setTitle('导出经销商信息');
	//表头设置
	//表头设置 start
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 1, '编号', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 1, '经销商编号', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 1, '经销商名称', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, 1, '经销商类型', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, 1, 'K3编码', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, 1, '经销商默认折扣返点', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, 1, '后返比率', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7, 1, '业务联系人', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8, 1, '业务联系人电话', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(9, 1, '身份证号码', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(10, 1, '营业执照号码', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(11, 1, '大区', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(12, 1, '省名称', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(13, 1, '市名称', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(14, 1, '操作模式', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(15, 1, '注册资本', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(16, 1, '法人代表', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(17, 1, '开户行', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(18, 1, '开户行账号', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(19, 1, '税号', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(20, 1, '财务联系人', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(21, 1, '财务联系人号码', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(22, 1, '发票寄送地址', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(23, 1, '税务注册地址', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(24, 1, '税务注册电话', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(25, 1, '备注', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(26, 1, '余额', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(27, 1, '后返余额', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(28, 1, '签约状态', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(29, 1, '签约日期', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(30, 1, '合同开始时间', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(31, 1, '合同结束时间', true)->getStyle()->getFont()->setBold(true);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(32, 1, '用户状态', true)->getStyle()->getFont()->setBold(true);
	
	
	// 搜索条件start
	$condition_array = array();
	
	
	
	if(!empty($params_en['dealer_name'])){
		array_push($condition_array, "di.dealer_name LIKE '%".$params_en['dealer_name']."%'");
	}
	
	
	if(!empty($params_en['dealer_type'])){
		array_push($condition_array, "di.dealer_type = ".$params_en['dealer_type']."");
	}
	
    if(!empty($params_en['area_name'])){
		array_push($condition_array, "di.area_name LIKE '%".$params_en['area_name']."%'");
	}
	if(!empty($params_en['business_leader'])){
		array_push($condition_array, "di.business_leader LIKE '%".$params_en['business_leader']."%'");
	}
	if(!empty($params_en['status'])){
		array_push($condition_array, "di.status = ".$params_en['status']."");
	}
	if(!empty($params_en['sign_status'])){
		array_push($condition_array, "di.sign_status = ".$params_en['sign_status']."");
	}
	if(!empty($params_en['dealer_channel'])){
		array_push($condition_array, "di.dealer_channel = ".$params_en['dealer_channel']."");
	}
	
	
	if (! empty ($params_en['k3_code']  )) {
	
		if($params_en['k3_code'] == 1 ){
			array_push($condition_array,"di.k3_code IS NOT  NULL  AND di.k3_code !='' AND di.k3_code != 'None'");
			
		}else {
		
			array_push($condition_array,"(di.k3_code IS NULL OR di.k3_code = 'None' OR di.k3_code = '')");
		}
	}

	$condition_sql = implode(' AND ', $condition_array);
	
	
	
	$dealer_lst = M('dealer_info')->alias('di')->where($condition_sql)->select();
	$row_num = 2;
	foreach ($dealer_lst as $dealer){
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,  $row_num, $row_num-1);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,  $row_num, $dealer['dealer_id']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,  $row_num, $dealer['dealer_name']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,  $row_num, StringBiz::getDealerTypeRevenueStatusText($dealer['dealer_type']));
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(4,  $row_num, $dealer['k3_code']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(5,  $row_num, $dealer['discount_rate']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(6,  $row_num, $dealer['cash_back_rate']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(7,  $row_num, $dealer['business_leader']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(8,  $row_num, ''.$dealer['business_leader_cellphone']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(9,  $row_num, ''.$dealer['dealer_id_card_no']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(10, $row_num, ''.$dealer['business_license_no']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(11, $row_num, $dealer['area_name']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(12, $row_num, $dealer['province_name']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(13, $row_num, $dealer['city_name']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(14, $row_num, $dealer['operation_pattern']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(15, $row_num, ''.$dealer['registered_capital']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(16, $row_num, $dealer['leal_person']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(17, $row_num, $dealer['bank_name']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(18, $row_num, $dealer['bank_no']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(19, $row_num, $dealer['tax_no']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(20, $row_num, $dealer['finance_leader']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(21, $row_num, ''.$dealer['finance_leader_cellphone']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(22, $row_num, $dealer['invoice_address']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(23, $row_num, $dealer['registered_address']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(24, $row_num, $dealer['registered_tel']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(25, $row_num, $dealer['remark']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(26, $row_num, $dealer['amount']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(27, $row_num, $dealer['cashback_amount']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(28, $row_num, StringBiz::getDealerSignStatusRevenueStatusText($dealer['sign_status']));
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(29, $row_num, $dealer['sign_date']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(30, $row_num, $dealer['contract_start_date']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(31, $row_num, $dealer['contract_end_date']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(32, $row_num, StringBiz::getDealerStatusRevenueStatusText($dealer['status']));
		$row_num = $row_num + 1;
	}
	
	
	return $objPHPExcel;
	
}
	
	
	
	
	
	
	
	
	
	

    // =============================================================================
    // ========================== 经销商余额 Begin ==================================
    // =============================================================================

    /**
     * 经销商订单余额支付
     * @param $order_id 订单编号
     * @param $dealer_en 经销商实体
     * @param $dealer_amount 需支付的账户余额
     * @param $dealer_cashback_amount 需支付的返现余额
     */
    public static function DealerOrderAmountPayment($order_id, $dealer_en, $dealer_amount, $dealer_cashback_amount){
        $dealer_id  =$dealer_en['dealer_id'];

        // ============= 1、变更余额 begin =============
        $dealer_new_amount = $dealer_en['amount'] - $dealer_amount;
        M('dealer_info')
            ->where("dealer_id='%s'", $dealer_id)
            ->setField('amount', $dealer_new_amount);
        //插入经销商余额表
        $dealer_amount = array(
            "dealer_amount_id"	=> DealerBiz::generateDealerAmountId(),
            "dealer_id"   =>$dealer_en['dealer_id'],
            "dealer_name" =>$dealer_en['dealer_name'],
            "amount_kind" =>2,//减少
            "amount_type" =>24,//订单支付
            "amount"      =>$dealer_amount,//订单金额
            "begin_amount"=>$dealer_en['amount'],
            "end_amount"  =>$dealer_new_amount,
            "order_id"    =>$order_id,
            "remark" =>"订单支付",
            "status" =>1,//有效
            'create_user' => "whaleyinfo.order DealerBiz.DealerOrderAmountPayment",
            'create_date' => date ( "y-m-d H:i:s", time () )
        );
        M('dealer_amount')->add($dealer_amount);
        // ============= 1、变更余额 End =============


        // ============= 2、变更返现余额 begin =============
        if($dealer_cashback_amount > 0){
            $dealer_new_cashback_amount = $dealer_en['cashback_amount'] - $dealer_cashback_amount;
            M('dealer_info')
                ->where("dealer_id='%s'", $dealer_id)
                ->setField('cashback_amount', $dealer_new_cashback_amount);
            $dealer_cashback_amount = array(
                "dealer_amount_id"	=> DealerBiz::generateDealerAmountId(),
                "dealer_id"   =>$dealer_en['dealer_id'],
                "dealer_name" =>$dealer_en['dealer_name'],
                "amount_kind" =>2,//减少
                "amount_type" =>24,//订单支付
                "amount"      =>$dealer_cashback_amount,
                "begin_amount"=>$dealer_en['cashback_amount'],
                "end_amount"  =>$dealer_new_cashback_amount,
                "order_id"    =>$order_id,
                "remark" =>"订单支付",
                "status" =>1,//有效
                'create_user' => "whaleyinfo.order DealerBiz.DealerOrderAmountPayment",
                'create_date' => date ( "y-m-d H:i:s", time () )
            );
            M('dealer_cashback_amount')->add($dealer_cashback_amount);

        }
        // ============= 2、变更返现余额 End =============


        // ============= 3、变更订单与支付状态 begin =============
        /**
         * 注意：此处虽已支付，但不变更订单状态为22（已支付），以契合审批流，待财务审批通过后订单状态再变为已支付
         */
        M('order_info')
            ->where("order_id='%s'", $order_id)
            ->setField('payment_status', 1);

        M('order_payment')
            ->where("order_id='%s'", $order_id)
            ->setField("payment_status",1);
        // ============= 3、变更订单与支付状态 end =============
    }




    // =============================================================================
    // ========================== 经销商余额 End =====================================
    // =============================================================================







    // =============================================================================
    // ========================== 订单相关 Begin ====================================
    // =============================================================================

    /**
     * 经销商提交订单
     * @param $dealer_id
     * @param $select_address_id
     * @param $sku_list_str
     * @param $remark
     * @param $order_id
     * @param $payment_type
     * @param $addDiscountAmount
     * @param $subDiscountAmount
     * @param $dealer_amount
     * @param $dealer_cashback_amount
     * @return string
     */
	public static function submitDealerOrder($dealer_id, $select_address_id,
                                             $sku_list_str, $remark, $order_id, $payment_type,
                                             $addDiscountAmount,$subDiscountAmount,
                                             $dealer_cashback_amount = 0)
    {


        // ============= 参数校验与格式化 begin =============


        //返现余额需支出的金额
        $dealer_cashback_amount = doubleval($dealer_cashback_amount);


        // 1、购物车商品数据
        if (empty ($sku_list_str)) {
            return '未选择商品';
        }

        // 2、经销商数据校验
        if (empty ($dealer_id)) {
            return '未选择经销商';
        }
        $dealer_en = M('dealer_info')->where("dealer_id='$dealer_id'")->find();


        // 3、地址信息校验
        if (empty ($select_address_id)) {
            return '未选择地址信息';
        }
        $user_address_en = M('user_address')->where("address_id='$select_address_id'")->find();
        if (empty($user_address_en)) {
            return '无效的地址信息';
        }

        // 4、数据初始化
        $user_id = cookie('login_user_id');
        $sku_channel    = StringBiz::getSkuChannelByDealerChannel($dealer_en['dealer_channel']);
        $order_type     = StringBiz::getOrderTypeByDealerChannel($dealer_en['dealer_channel']);
        // ============= 参数校验与格式化 End =============


        // ============= 购物车数格式化与校验 Begin =============
        $cart_en = OrderBiz::calcCart($sku_list_str, $sku_channel);
        $lst_buy_sku = $cart_en['lst_sku_en'];

        $total_sku_count = 0;
        foreach ($lst_buy_sku as $key => $sku_en) {
            $total_sku_count = $total_sku_count + $sku_en['qty'];
        }

        if($order_type == 8) {
            if ($total_sku_count < 10) {
                return '下单的商品数量必需大于或等于10';
            }
        }
        // ============= 购物车数据格式化与校验 End =============



        //region ============= 【*】经销商订单业务逻辑计算金额与订单明细【*】 Begin =============
        //记录订单真实支付金额
        $all_payment_amount = 0;
        //记录订单经销商前返金额
        $all_dealear_rate_amount = 0;

        foreach ( $lst_buy_sku as $key => $sku_en ) {
            //1、判断是否有业务员指定价格
            $payment_price   = $sku_en['payment_price'];
            if(!$sku_en['payment_price']){
                //无指定价格
                $lst_buy_sku[$key]['payment_price']   = $sku_en['payment_price'];
                $payment_price      = $sku_en['sale_price'];
                if ($sku_en ['is_rebate'] == '1') {
                    $payment_price  = $sku_en['sale_price'] - $sku_en['sale_price'] * $dealer_en ['discount_rate'];
                    $all_dealear_rate_amount    += $sku_en['sale_price'] * $dealer_en ['discount_rate'] * $sku_en['qty'];
                }
            }
            $lst_buy_sku[$key]['payment_price']   = $payment_price;

            //2、校验是否超过最低限价
            if(!empty($sku_en['dealer_min_limit_price'])){
                if($payment_price < $sku_en['dealer_min_limit_price']){
                    return $sku_en['sku_name'].'超过最低价格'.$sku_en['dealer_min_limit_price'];
                }
            }


            //3、运算订单真实支付金额和经销商的前返金额
            $all_payment_amount         += $payment_price * $sku_en['qty'];
        }        
        //endregion  ============= 【*】经销商订单业务逻辑计算金额与订单明细【*】 End =============


        // ============= 订单参数格式化与校验 Begin =============
        //按逻辑获取支付方式
        $payment_method = 40;
        if($payment_type == 3){
            if($dealer_cashback_amount == 0){
                $payment_method = 30;
            }
            else{
                $payment_method = 31;
            }
        }
        else{
            $payment_method = 40;
        }
        
        
        //设置支付时间与支付状态
        $payment_status	= 0;
        $payment_date	= null;
        if($payment_type == 3){
        	//如果是在线支付，则支付状态为已支付兵时间是当前时间
        	$payment_status = 1;
        	$payment_date	= date ( "y-m-d H:i:s", time () );
        }

        //余额支付
        //账户余额需支付的金额
        $dealer_amount = 0;
        if($payment_type == 3){
            $dealer_amount  = $all_payment_amount - $dealer_cashback_amount;
            if(doubleval($dealer_en['amount']) < $dealer_amount){

                return '用户余额不足';
            }


            if(doubleval($dealer_en['cashback_amount']) < $dealer_cashback_amount){
                return '用户返现余额不足';
            }

            if($dealer_cashback_amount > 0){
                if($dealer_cashback_amount > $all_payment_amount * 0.5){
                    return '返利余额不可大于订单金额的50%';
                }
            }
        }
        // ============= 订单参数格式化与校验 End =============


        // ============= 数据库写入记录 Begin =============
        //1、写入order_detail(东方有线DL1739763同时要写入日日顺发货表)
        $oid_num = 100;
        $order_date = date ( "y-m-d H:i:s", time () );

        //以下记录用来分配余额支付和返现余额支付
        $already_dealer_amount			= 0;
        $already_dealer_cashback_amount	= 0;
        
        $sku_count	= count($lst_buy_sku);
        
        for($i=0; $i<$sku_count; $i++){
        	$sku_en = $lst_buy_sku[$i];
        	
        	if(intval($sku_en['qty']) == 0){
        		continue;
        	}
        	
        	
        	// ==== 计算订单行的余额和返现余额分摊 begin ====
        	$order_detail_dealer_amount			= 0;
        	$order_detail_dealer_cashback_amount= 0;
        	
        	if($i == $sku_count - 1){
        		//最后一行订单行
        		$order_detail_dealer_amount	= $dealer_amount - $already_dealer_amount;
        		$order_detail_dealer_cashback_amount = $dealer_cashback_amount - $already_dealer_cashback_amount;
        	}
        	else{
        		//非最后一行订单行
        		$order_detail_dealer_amount		= round(($sku_en ['qty'] * $sku_en ['payment_price']) * ($dealer_amount / $all_payment_amount), 2);         		
        		$order_detail_dealer_cashback_amount	= round(($sku_en ['qty'] * $sku_en ['payment_price']) * ($dealer_cashback_amount / $all_payment_amount), 2);
        		$already_dealer_amount	= $already_dealer_amount + $order_detail_dealer_amount;
        		$already_dealer_cashback_amount = $already_dealer_cashback_amount + $order_detail_dealer_cashback_amount;
        	}
        	// ==== 计算订单行的余额和返现余额分摊 end   ====
        	
        	
        	// ==== 写入order_detail begin ====
        	$third_oid = $order_id . strval ( $oid_num );
        	self::insertOrderDetail ( $order_id, $third_oid, $sku_en ,
        			$order_detail_dealer_amount, $order_detail_dealer_cashback_amount);
        	// ==== 写入order_detail End ====
        	
        	
        	// ==== 写入rrs_stock_order begin ====
        	if($dealer_id = 'DL1739763'){
        		//东方有线渠道
        		$recive_district_id		= $user_address_en['consignee_district_id'];
        		$rrsShippingRegion_en	= M('rrsShippingRegion', '', 'DB_whaley_trade')->where("recive_district_id = '%s' AND warehouse_code IS NOT NULL", $recive_district_id)->find();
        		self::insertRrsStockOrder($order_id, $third_oid, $order_date, $sku_en, $user_address_en, $rrsShippingRegion_en, $dealer_en);
        	}
        	// ==== 写入rrs_stock_order End ====
        	
        	$oid_num = $oid_num + 1;
        }
        

        //2、写入order_discount
        if(!empty($addDiscountAmount)){
            self::saveOrderDiscount($order_id, '41', '经销商价格上浮', '-'.$addDiscountAmount);
        }

        if(!empty($subDiscountAmount)){
            self::saveOrderDiscount($order_id, '42', '经销商价格下调', $subDiscountAmount);
        }

        //返现余额也视为一种折扣
        if($dealer_cashback_amount > 0){
            self::saveOrderDiscount($order_id, '43', '经销商返现余额支付', $dealer_cashback_amount);
        }

        //经销商先返金额是一种折扣
        if($all_dealear_rate_amount > 0){
            self::saveOrderDiscount($order_id, '44', '经销商返现余额支付', $all_dealear_rate_amount);
        }

        //计算整张订单的折扣金额
        $order_discount_fee = $dealer_cashback_amount + $all_dealear_rate_amount + $subDiscountAmount - $addDiscountAmount;
        //3、写入order_info
        $order_info_en = array (
            'order_id'      => $order_id,
            'order_status'  => 10,
            'order_type'    => StringBiz::getOrderTypeByDealerChannel($dealer_en['dealer_channel']),
            'payment_type'  => $payment_type,
            'payment_method'=> $payment_method,
            'payment_status'=> $payment_status,
            'user_id'       => $user_address_en ['user_id'],
            'seller_alipay_no'  => $user_id,
            'seller_name'   => $user_id,
            'buyer_alipay_no'   => $dealer_en ['dealer_id'],
            'buyer_name'    => $dealer_en ['dealer_name'],
            'buyer_mobile'  => $user_address_en ['consignee_cellphone'],
            'buyer_ip'      => get_client_ip (),
            'invoice_kind'  => 23,
            'invoice_status'=> 1,
            'invoice_name'  => '个人',
            'buyer_message' => $remark,
            'address_id'    => $select_address_id,
            'consignee_name'=> $user_address_en ['consignee_name'],
            'consignee_cellphone'   => $user_address_en ['consignee_cellphone'],
            'consignee_province_id' => $user_address_en ['consignee_province_id'],
            'consignee_province'    => $user_address_en ['consignee_province'],
            'consignee_city_id'     => $user_address_en ['consignee_city_id'],
            'consignee_city'=> $user_address_en ['consignee_city'],
            'consignee_district_id' => $user_address_en ['consignee_district_id'],
            'consignee_district'    => $user_address_en ['consignee_district'],
            'consignee_address'     => $user_address_en ['consignee_address'],
            'consignee_zip' => $user_address_en ['consignee_zip'],
            'goods_amount'  => $cart_en['goods_amount'],
            'goods_qty'     => $cart_en['goods_qty'],
            'actual_payment'=> $all_payment_amount - $dealer_cashback_amount,
            'payment_amount'=> $all_payment_amount,
            'freight'       => 0,
            'discount_fee'  => $order_discount_fee,
            'order_amount'  => $all_payment_amount,
            'cash_back_status'  => 1,
            'order_date'    => $order_date,
            'create_user'   => 'whaleytrade.AjaxService.Dealer.submitDealerOrder',
            'create_date'   => date ( "y-m-d H:i:s", time () )
        );
        //默认发票形式为:23|微鲸纸质专票 当经销商为个体工商户  dealer_type.dealer_type = 2时候 发票形式变更为: 22| 微鲸纸质发票
        if($dealer_en['dealer_type'] == 2){
        	$order_info_en['invoice_kind'] = 22;
        }
        M ( 'order_info' )->add ( $order_info_en );

        //4、写入order_payment
        $order_payment_en = array (
            'order_id' => $order_id,
            'payment_type' => $payment_type,
            'payment_method' => $payment_method,
            'payment_status' => $payment_status,
            'freight' => 0,
            'actual_payment' => $all_payment_amount - $dealer_cashback_amount,
            'payment_amount' => $all_payment_amount,
        	'payment_date'	 => $payment_date,
            'account_payment_type'  => 3,
            'account_id'     => $dealer_en ['dealer_id'],
            'account_amount' => $dealer_amount,
            'cashback_account_amount'   => $dealer_cashback_amount,
            'create_user' => 'whaleytrade.AjaxService.Dealer.submitDealerOrder',
            'create_date' => date ( "y-m-d H:i:s", time () )
        );
        M ( 'order_payment' )->add ( $order_payment_en );

        //5、写入order_status_change_log
        $order_status_change_log = array (
            'order_id' => $order_id,
            'order_status' => 10,
            'order_status_text' => '已提交',
            'remark' => '',
            'create_user' => 'whaleytrade.AjaxService.Dealer.submitDealerOrder',
            'create_date' => date ( "y-m-d H:i:s", time () )
        );
        M ( 'orderStatusChangeLog' )->add ( $order_status_change_log );


        //6、若是余额支付，扣减经销商余额与返现余额
        if($payment_type == 3){
            DealerBiz::DealerOrderAmountPayment($order_id, $dealer_en, $dealer_amount, $dealer_cashback_amount);
        }
        // ============= 数据库写入记录  End=============
	}
	
	/**
	 *
	 * @param unknown $order_id
	 *        	订单编号
	 * @param unknown $third_oid
	 *        	第三方子订单编号（对应order_detail表同字段）
	 * @param unknown $buy_sku_en
	 *        	购买的sku的信息
	 */
	public static function insertOrderDetail($order_id, $third_oid, $buy_sku_en, $order_detail_dealer_amount, $order_detail_dealer_cashback_amount) {
		$order_detail_en = array (
				'oid'       => $third_oid,
				'order_id'  => $order_id,
				'third_oid' => $third_oid,
				'style_id'  => $buy_sku_en ['style_id'],
				'style_name'=> $buy_sku_en ['style_name'],
				'sku_id'    => $buy_sku_en ['sku_id'],
				'third_sku_id'  => $buy_sku_en ['sku_sn'],
				'sku_properties_name'   => $buy_sku_en ['sku_name'],
				'sku_name'  => $buy_sku_en ['sku_name'],
				'qty'       => $buy_sku_en ['qty'],
				'market_price'  => $buy_sku_en ['sale_price'],
				'sale_price'    => $buy_sku_en ['sale_price'],
				'goods_payment_amount'  => $buy_sku_en ['payment_price'],
				'account_amount'		=> $order_detail_dealer_amount,
				'cashback_account_amount'	=> $order_detail_dealer_cashback_amount,
				'image'     		=> $buy_sku_en ['image'],
				'payment_amount'    => $buy_sku_en ['qty'] * $buy_sku_en ['payment_price'],
				'divide_order_fee'  => $buy_sku_en ['qty'] * $buy_sku_en ['payment_price'],
				'invoice_status'  => 1,
				'create_user'       => 'whaleytrade.AjaxService.Dealer.submitDealerOrder',
				'create_date'       => date("y-m-d H:i:s", time())
		);
		M ( 'order_detail' )->add ( $order_detail_en );
		return $order_detail_en;
	}
	
	
	/**
	 * 向rrs_stock_order写入数据
	 * @param unknown $order_id 订单编号
	 * @param unknown $third_oid 第三方子订单编号（对应order_detail表同字段）
	 * @param unknown $buy_sku_en 购买的sku的信息
	 * @param unknown $user_address_en 收货人的地址信息
	 * @param unknown $rrsShippingRegion_en rrs配送地址信息
	 */
	public static function insertRrsStockOrder($order_id, $third_oid, $order_date, $buy_sku_en, $user_address_en, $rrsShippingRegion_en, $dealer_en){
	
		$rrs_stock_order_id = ''.$third_oid;
		$insertRrs_stock_order_add = array(
				'rrs_stock_order_id'	=>	$rrs_stock_order_id,
				'order_id'				=>	$order_id,
				'third_oid'				=>	$third_oid,
				'promoter_id'			=> 	$dealer_en['dealer_id'],
				'promoter_name'			=> 	$dealer_en['dealer_name'],
				'order_date'			=>  $order_date,
				'order_type'			=>  8,
				'rrs_stock_order_type'	=>	1,
				'cod_amount'			=>	0,
				'consignee_name'		=>	$user_address_en['consignee_name'],
				'consignee_cellphone'	=>	$user_address_en['consignee_cellphone'],
				'consignee_tel'			=> '',
				'consignee_province_id'	=>  $rrsShippingRegion_en['recive_province_id'],
				'consignee_province'	=>  $rrsShippingRegion_en['recive_province_name'],
				'consignee_city_id'		=>  $rrsShippingRegion_en['recive_city_id'],
				'consignee_city'		=>  $rrsShippingRegion_en['recive_city_name'],
				'consignee_district_id'	=>  $rrsShippingRegion_en['recive_district_id'],
				'consignee_district'	=>  $rrsShippingRegion_en['recive_district_name'],
				'consignee_address'		=>	$user_address_en['consignee_address'],
				'material_no'			=>	$buy_sku_en['material_no'],
				'goods_qty'				=>	$buy_sku_en['qty'],
				'batch'					=>	'正品',
				'send_warehouse_code'	=>	$rrsShippingRegion_en['warehouse_code'],
				'send_warehouse_name'	=>	$rrsShippingRegion_en['warehouse_name'],
				'create_user'			=> 'whaleytrade.AjaxService.Dealer.submitDealerOrder',
				'create_date'			=> date("y-m-d H:i:s", time())
		);
		M('rrsStockOrder', '', 'DB_whaley_trade')->add($insertRrs_stock_order_add);
	}
	
	
	
	public static function saveOrderDiscount($order_id, $discountType,$discount_name,$discountAmount) {
		$order_discount_en = array (
				'order_id' => $order_id,
				'third_order_id' => $order_id,
				'third_oid' => $order_id,
				'discount_type' => $discountType,
				'discount_name' => $discount_name,
				'discount_amount' => $discountAmount,
				'dicount_desc' => $discount_name,
				'promotion_id' => $order_id.$discountType,
				'create_user' => 'whaleytrade.AjaxService.Dealer.DealerBiz',
				'create_date' => date ( "y-m-d H:i:s", time () )
		);
		M ( 'order_discount' )->add ( $order_discount_en );
		
	}
	
// 	public static function insertRrsStockOrder($order_id, $third_oid, $order_date, $buy_sku_en, $user_address_en, $rrsShippingRegion_en, $dealer_en) {
// 		$rrs_stock_order_id = '' . $third_oid;
// 		$insertRrs_stock_order_add = array (
// 				'rrs_stock_order_id' => $rrs_stock_order_id,
// 				'order_id' => $order_id,
// 				'third_oid' => $third_oid,
// 				'promoter_id' => $dealer_en ['dealer_id'],
// 				'promoter_name' => $dealer_en ['dealer_name'],
// 				'order_date' => $order_date,
// 				'order_type' => 8,
// 				'rrs_stock_order_type' => 1,
// 				'cod_amount' => 0,
// 				'consignee_name' => $user_address_en ['consignee_name'],
// 				'consignee_cellphone' => $user_address_en ['consignee_cellphone'],
// 				'consignee_tel' => '',
// 				'consignee_province_id' => $rrsShippingRegion_en ['recive_province_id'],
// 				'consignee_province' => $rrsShippingRegion_en ['recive_province_name'],
// 				'consignee_city_id' => $rrsShippingRegion_en ['recive_city_id'],
// 				'consignee_city' => $rrsShippingRegion_en ['recive_city_name'],
// 				'consignee_district_id' => $rrsShippingRegion_en ['recive_district_id'],
// 				'consignee_district' => $rrsShippingRegion_en ['recive_district_name'],
// 				'consignee_address' => $user_address_en ['consignee_address'],
// 				'material_no' => $buy_sku_en ['material_no'],
// 				'goods_qty' => $buy_sku_en ['qty'],
// 				'batch' => '正品',
// 				'send_warehouse_code' => $rrsShippingRegion_en ['warehouse_code'],
// 				'send_warehouse_name' => $rrsShippingRegion_en ['warehouse_name'],
// 				'create_user' => 'whaleyFZ.AjaxService.order.submitOrder',
// 				'create_date' => date ( "y-m-d H:i:s", time () ) 
// 		);
// 		M ( 'rrsStockOrder', '', 'DB_whaley_trade' )->add ( $insertRrs_stock_order_add );
// 	}


    // =============================================================================
    // ========================== 订单相关 End ======================================
    // =============================================================================

	/**
	 *
	 * @param
	 *        	$file_path
	 * @return string
	 * @throws \PHPExcel_Reader_Exception
	 */
	public static function stockOrderImport($file_path) {
		Vendor ( "phpExcel.PHPExcel.IOFactory" );
		if (! file_exists ( $file_path )) {
			return 'file not find';
		}
		
		$objReader = \PHPExcel_IOFactory::createReader ( 'Excel5' );
		$PHPReader = $objReader->load ( $file_path );
		
		$PHPReader->setActiveSheetIndex ( 0 );
		$sheet = $PHPReader->getActiveSheet (); // 读取第一個工作表
		$highestRow = $sheet->getHighestRow (); // 取得总行数
		
		$lst_rrs_import_stock_order_en = array ();
		$lst_rrs_stock_order_id = array ();
		for($row = 1; $row <= $highestRow; $row ++) { // 行数是以第1行开始
			$logistics_status_text = $sheet->getCellByColumnAndRow ( 0, $row )->getValue ();
			$rrs_stock_order_id = $sheet->getCellByColumnAndRow ( 1, $row )->getValue ();
			$logistics_no = $sheet->getCellByColumnAndRow ( 2, $row )->getValue ();
			// 签收状态
			$logistics_sign_flag = 0;
			
			if ($logistics_status_text == '签收成功') {
				$logistics_sign_flag = 1;
			} else {
				$logistics_sign_flag = 0;
			}
			
			$rrs_import_stock_order_en = array (
					'rrs_stock_order_id' => $rrs_stock_order_id,
					'logistics_no' => $logistics_no,
					'logistics_sign_flag' => $logistics_sign_flag 
			);
			array_push ( $lst_rrs_import_stock_order_en, $rrs_import_stock_order_en );
			array_push ( $lst_rrs_stock_order_id, $rrs_stock_order_id );
		}
		



		self::ProccessImportStockOrder ( $lst_rrs_stock_order_id, $lst_rrs_import_stock_order_en );
	}
	
	
	
	/**
	 *
	 * @param
	 *        	$file_path
	 * @return string
	 * @throws \PHPExcel_Reader_Exception
	 */
	public static function k3_coder_order_import($file_path) {
		Vendor ( "phpExcel.PHPExcel.IOFactory" );
		if (! file_exists ( $file_path )) {
			return 'file not find';
		}
		$objReader = \PHPExcel_IOFactory::createReader ( 'Excel5' );
		$PHPReader = $objReader->load ( $file_path );
		$PHPReader->setActiveSheetIndex ( 0 );
		$sheet = $PHPReader->getActiveSheet (); // 读取第一個工作表
		$highestRow = $sheet->getHighestRow (); // 取得总行数
		$total_row=$highestRow-1;//总共多少条记录
		$success=0;//执行成功次数
		$failure=0;//执行失败次数
		$error_dealers=array();
		for($row = 2; $row <= $highestRow; $row ++) { // 行数是以第1行开始
			$logistics_status_text = $sheet->getCellByColumnAndRow ( 0, $row )->getValue ();
			$k3_code= $sheet->getCellByColumnAndRow ( 1, $row )->getValue ();
			$dealer_name = $sheet->getCellByColumnAndRow ( 2, $row )->getValue ();
			$result=M ( 'dealer_info' )->where ( "dealer_name='$dealer_name'" )->setField ( 'k3_code', $k3_code );
			if($result>=1){
				$success++;
			}else{
				array_push($error_dealers, $dealer_name) ;					
				$failure++;
			}
		}
		$dealer_info_en = array (
				'total_row' => $total_row,
				'success' => $success,
				'failure' => $failure,
				'error_dealers'=>join("<br>",$error_dealers )
		);
		
// 		echo "total:".$total_row." success：".$success." failure:".$failure.".";
// 		echo "失败经销商名称：".join("\r\n", json_encode($error_dealers));
		return $dealer_info_en;
		
	}
	
	
	/**
	 *
	 * @param unknown $lst_rrs_stock_order_id
	 *        	所有rrs出库单的编号集合
	 * @param unknown $lst_rrs_import_stock_order_en
	 *        	所有rrs出库单的数据集合
	 */
	private static function ProccessImportStockOrder($lst_rrs_stock_order_id, $lst_rrs_import_stock_order_en) {
		$lst_rrs_stock_order_id_condition_sql = "rrs_stock_order_id IN ('" . implode ( "','", $lst_rrs_stock_order_id ) . "')";
		$lst_rrsStockOrder_en = M ( 'rrsStockOrder', '', 'DB_whaley_trade' )->where ( $lst_rrs_stock_order_id_condition_sql )->select ();
		
		// 本次导入所涉及到的订单编号集合
		$lst_import_order_id = array ();
		
		// 1.更改订单详情数据begin
		foreach ( $lst_rrs_import_stock_order_en as $rrs_import_stock_order_en ) {
			$rrs_stock_order_id = $rrs_import_stock_order_en ['rrs_stock_order_id'];
			$logistics_no = $rrs_import_stock_order_en ['logistics_no'];
			$logistics_sign_flag = $rrs_import_stock_order_en ['logistics_sign_flag'];
			
			$filter_lst_rrsStockOrder_en = array_filter ( $lst_rrsStockOrder_en, function ($rrsStockOrder_item) use ($rrs_stock_order_id) {
				return $rrsStockOrder_item ['rrs_stock_order_id'] == $rrs_stock_order_id;
			} );
			if (empty ( $filter_lst_rrsStockOrder_en )) {
				continue;
			}
			
			$rrsStockOrder_en = current ( $filter_lst_rrsStockOrder_en );
			array_push ( $lst_import_order_id, $rrsStockOrder_en ['order_id'] );
			
			// 更新order_detail表的物流信息begin
			$logistics_status = 1;
			if (empty ( $logistics_no )) {
				// 物流处理中
				$logistics_status = 1;
			} else {
				if ($logistics_sign_flag == 0) {
					// 已发货
					$logistics_status = 2;
				} else {
					// 已签收
					$logistics_status = 3;
				}
			}
			
			$update_order_detail_en = array (
					'shipping_type' => 22,
					'logistics_no' => $logistics_no,
					'logistics_company' => '日日顺',
					'logistics_status' => $logistics_status 
			);
			
			M ( 'orderDetail', '', 'DB_whaley_trade' )->where ( array (
					'third_oid' => $rrsStockOrder_en ['third_oid'] 
			) )->save ( $update_order_detail_en );
		}
		
		// 1.更改订单详情数据end
		
		// 2.更改订单状态begin
		$lst_order_id_condition_sql = "order_id IN ('" . implode ( "','", $lst_import_order_id ) . "')";
		$lst_order_detail_en = M ( 'orderDetail', '', 'DB_whaley_trade' )->where ( $lst_order_id_condition_sql )->select ();
		
		foreach ( $lst_import_order_id as $order_id ) {
			$filter_lst_orderDetail_en1 = array_filter ( $lst_order_detail_en, function ($order_detail_item) use ($order_id) {
				return ($order_detail_item ['order_id'] == $order_id && $order_detail_item ['logistics_status'] == 1);
			} );
			
			$order_status = 25;
			
			if (! empty ( $filter_lst_orderDetail_en1 )) {
				// 只要存在一个物流状态1为（物流处理中），那订单状态就是25
				$order_status = 25; // 物流处理中
			} else {
				$filter_lst_orderDetail_en2 = array_filter ( $lst_order_detail_en, function ($order_detail_item) use ($order_id) {
					return ($order_detail_item ['order_id'] == $order_id && $order_detail_item ['logistics_status'] == 2);
				} );
				
				if (! empty ( $filter_lst_orderDetail_en2 )) {
					// 不存在物流状态为1（物流处理中），只要存在任一物流状态为2（已发货），则订单状态就是31
					$order_status = 31; // 已发货
				} else {
					$filter_lst_orderDetail_en3 = array_filter ( $lst_order_detail_en, function ($order_detail_item) use ($order_id) {
						return ($order_detail_item ['order_id'] == $order_id && $order_detail_item ['logistics_status'] == 3);
					} );
					
					$filter_all_lst_orderDetail_en3 = array_filter ( $lst_order_detail_en, function ($order_detail_item) use ($order_id) {
						return ($order_detail_item ['order_id'] == $order_id);
					} );
					
					if (count ( $filter_lst_orderDetail_en3 ) == count ( $filter_all_lst_orderDetail_en3 )) {
						// 只有一张订单下的所有detail物流全部是3（已签收），此张订单状态才为35
						$order_status = 35; // 已完成
					} else {
						$order_status = 26; // 物流异常
					}
				}
			}
			
			// A.更改order_info的订单状态
			$update_orderInfo_en = array (
					'order_status' => $order_status 
			);
			if ($order_status == 35) {
				$update_orderInfo_en ['order_end_date'] = date ( "y-m-d H:i:s", time () );
			}
			
			M ( 'orderInfo', '', 'DB_whaley_trade' )->where ( "order_id='%s'", $order_id )->save ( $update_orderInfo_en );
		}
		// 2.更改订单状态end
	}
	public static function checkDealerMinSalePrice($dealer_id, $sku_list_str) {
		// 提交订单参数校验begin
		if (empty ( $dealer_id )) {
			return '未选择经销商';
		}
		$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='$dealer_id'" )->find ();
		$lst_goods_info = explode ( "|", $sku_list_str );
		
		// 计算商品总数，折扣总价
		foreach ( $lst_goods_info as $goods_info ) {
			
			$sku_str = explode ( ",", $goods_info );
			$sku_id = $sku_str [0];
			$qty = intval ( $sku_str [1] );
			if ($qty > 0) {
				$sku_en = M ( 'sku', '', 'DB_whaley_product' )->where ( "sku_id='$sku_id'" )->find ();
				$sale_price = $sku_en ['sale_price'];
				
				$discount_price = $sale_price;
				
				if ($sku_en ['is_rebate'] == '1') {
				  $discount_price = $sku_en ['sale_price'] - $sku_en ['sale_price'] * $dealer_en ['discount_rate'];
				}
                   $discount_price = round($discount_price,2);
                    $MinPrice = $sku_en ['dealer_min_limit_price'];
				
				if (! empty ( $MinPrice ) && ($discount_price < $MinPrice)) {
					return $sku_en ['sku_name'] . '超过最低价格' . $MinPrice;
				}
			}
		}
	}
	public static function searchDearlerForOrder($dealer_id, $dealer_name,$dealer_channel) {
		$con = array ();
		array_push ( $con, "status=2" );
		
		array_push ( $con, "dealer_channel=".$dealer_channel );
		if (! empty ( $dealer_name )) {
			array_push ( $con, "dealer_name like '%$dealer_name%'" );
		}
		
		// if (!empty($dealer_id)) {
		// array_push($con, "dealer_id like '%$dealer_id%'");
		// }
		
		$lst_dealer_info = M ( 'dealer_info' )->where ( join ( " AND ", $con ) )->select ();
// 		echo M()->getLastSql();
		
		
		$sale_id = cookie ( 'login_user_id' );
		$sale_en = M ( 'sale_user' )->where ( "sale_name='%s'", $sale_id )->find ();
		
		if ($sale_en == null) {
		} else {
			$result = SaleBiz::queryDealerBySaleAndPara ( $sale_en ['sale_id'], $dealer_name, '', '', '', null, 2, '',$dealer_channel, 9999, 1 );
			$lst_dealer_info = $result ['datas'];
		}
		return $lst_dealer_info;
	}
	
	
	
	public function  shipDealerCashBackAmountExcel( $params_en){
		
		
		Vendor('phpExcel.PHPExcel');
		$objPHPExcel = new  \PHPExcel();
		
		$objPHPExcel->setActiveSheetIndex(0);
		$objPHPExcel->getActiveSheet()->setTitle('导出经销商后返余额信息');
		//表头设置
		//表头设置 start
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 1, '编号', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 1, '经销商编号', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 1, '经销商名称', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, 1, '变动种类', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, 1, '变动类型', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, 1, '变动前金额', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, 1, '变动金额', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7, 1, '变动后金额', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8, 1, '相关订单编号', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(9, 1, '备注', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(10, 1, '创建时间', true)->getStyle()->getFont()->setBold(true);
		//$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(11, 1, '充值状态', true)->getStyle()->getFont()->setBold(true);
		
		
		
		
		
		
		
		$dealer_id=$params_en['dealer_id'];
		$amount_type=$params_en['amount_type'];
		$dealer_channel=$params_en['dealer_channel'];
		$start_date= $params_en['start_date'];
		$end_date=  $params_en['end_date'];
		
		if (! empty ( $dealer_id )) {
			$condition_array ['dealer_id'] = array (
					'=',
					"'".$dealer_id."'"
			);
		}
		
		if (! empty ( $amount_type )) {
			$condition_array ['amount_type'] = array (
					'=',
					$amount_type
			);
		}
		
	/* 	if (! empty ( $start_date )) {
			$condition_array ['create_date'] = array (
					'>=',
					"'".$start_date."'"
			);
		} */
		
		if (! empty ( $end_date ) && ! empty ( $start_date )) {
			
			/* $condition_array ['create_date'] = array (
					'<=',
					"'".$end_date."'"
			); */
			
			
		
		}
		
		
		
		
		$temp = array();
		$cn=0;
		if(sizeof($condition_array)>0){
			$temp[]=" AND ";
		}
		foreach ($condition_array as $key=>$val){
		
			$temp[] ="dca.".$key.' ';
			$temp[] = join(" ", $val);
			if($cn != sizeof($condition_array)-1){
				$temp[]=" AND ";
			}
			$cn++;
		}
			
		$sql =  "exists (SELECT * FROM dealer_info AS di WHERE dca.dealer_id = di.dealer_id AND di.dealer_channel =".$dealer_channel ."".join('',$temp)." and dca.create_date between '$start_date' and '$end_date' ".")";
			
		
		$lst_dealers_amount = M ( 'dealer_cashback_amount' )->alias('dca')->field ()->where ( $sql )->order('create_date desc')->select ();
		
		
		$row_num = 2;
		
		foreach ($lst_dealers_amount as $dealer_amount){
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,  $row_num, $row_num-1);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,  $row_num, $dealer_amount['dealer_id']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,  $row_num, $dealer_amount['dealer_name']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,  $row_num, StringBiz::getDealerAmountKindRevenueStatusText($dealer_amount['amount_kind']));
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(4,  $row_num, StringBiz::getDealerAmountTypeRevenueStatusText($dealer_amount['amount_type']));
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(5,  $row_num, $dealer_amount['begin_amount']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(6,  $row_num, $dealer_amount['amount']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(7,  $row_num, $dealer_amount['end_amount']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(8,  $row_num, ''.$dealer_amount['order_id']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(9,  $row_num, ''.$dealer_amount['remark']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(10, $row_num, ''.$dealer_amount['create_date']);
			//$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(11, $row_num, StringBiz::getRechargeStatusText($dealer_amount['status']));
			$row_num = $row_num + 1;
		}
		
		
		return $objPHPExcel;
		
		
	}
	
	
	
	public function  shipDealerAmountExcel( $params_en){
	
	
		Vendor('phpExcel.PHPExcel');
		$objPHPExcel = new  \PHPExcel();
	
		$objPHPExcel->setActiveSheetIndex(0);
		$objPHPExcel->getActiveSheet()->setTitle('导出经销商余额信息');
		//表头设置
		//表头设置 start
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 1, '编号', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 1, '经销商编号', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 1, '经销商名称', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, 1, '变动种类', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, 1, '变动类型', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, 1, '变动前金额', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, 1, '变动金额', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7, 1, '变动后金额', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8, 1, '相关订单编号', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(9, 1, '备注', true)->getStyle()->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(10, 1, '创建时间', true)->getStyle()->getFont()->setBold(true);
		//$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(11, 1, '充值状态', true)->getStyle()->getFont()->setBold(true);
	
	
	
	
	
	
	
		$dealer_id=$params_en['dealer_id'];
		$amount_type=$params_en['amount_type'];
		$dealer_channel=$params_en['dealer_channel'];
		$start_date= $params_en['start_date'];
		$end_date=  $params_en['end_date'];
	
		if (! empty ( $dealer_id )) {
			$condition_array ['dealer_id'] = array (
					'=',
					"'".$dealer_id."'"
			);
		}
	
		if (! empty ( $amount_type )) {
			$condition_array ['amount_type'] = array (
					'=',
					$amount_type
			);
		}
	
		/* 	if (! empty ( $start_date )) {
		 $condition_array ['create_date'] = array (
		 '>=',
		 "'".$start_date."'"
		 );
			} */
	
		if (! empty ( $end_date ) && ! empty ( $start_date )) {
				
			/* $condition_array ['create_date'] = array (
			 '<=',
			 "'".$end_date."'"
				); */
				
				
	
		}
	
	
	
	
		$temp = array();
		$cn=0;
		if(sizeof($condition_array)>0){
			$temp[]=" AND ";
		}
		foreach ($condition_array as $key=>$val){
	
			$temp[] ="da.".$key.' ';
			$temp[] = join(" ", $val);
			if($cn != sizeof($condition_array)-1){
				$temp[]=" AND ";
			}
			$cn++;
		}
			
		$sql =  "exists (SELECT * FROM dealer_info AS di WHERE da.dealer_id = di.dealer_id AND di.dealer_channel =".$dealer_channel ."".join('',$temp)." and da.create_date between '$start_date' and '$end_date' ".")";
			
	
		$lst_dealers_amount = M ( 'dealer_amount' )->alias('da')->field ()->where ( $sql )->order('create_date desc')->select ();
	
	
		$row_num = 2;
	
		foreach ($lst_dealers_amount as $dealer_amount){
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,  $row_num, $row_num-1);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,  $row_num, $dealer_amount['dealer_id']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,  $row_num, $dealer_amount['dealer_name']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,  $row_num, StringBiz::getDealerAmountKindRevenueStatusText($dealer_amount['amount_kind']));
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(4,  $row_num, StringBiz::getDealerAmountTypeRevenueStatusText($dealer_amount['amount_type']));
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(5,  $row_num, $dealer_amount['begin_amount']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(6,  $row_num, $dealer_amount['amount']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(7,  $row_num, $dealer_amount['end_amount']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(8,  $row_num, ''.$dealer_amount['order_id']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(9,  $row_num, ''.$dealer_amount['remark']);
			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(10, $row_num, ''.$dealer_amount['create_date']);
			//$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(11, $row_num, StringBiz::getRechargeStatusText($dealer_amount['status']));
			$row_num = $row_num + 1;
		}
	
	
		return $objPHPExcel;
	
	
	}
}